<script lang="ts" setup>

import {useRoute, useRouter} from "vue-router";
import {onMounted, ref, watch} from "vue";
import {PriMsgRoute} from "../index.ts";
import {useMessageStore} from "../../store/MessageStore.ts";
import type {PriMsg, PriMsgBody} from "../../network/types/PrivateMessage.ts";
import {scrollToTop} from "../../utils/ScrollUtils.ts";
import type {UserInfo} from "../../network/types/User.ts";
import ReplyAuthorHeader from "../../components/reply/ReplyAuthorHeader.vue";
import {replaceAvatar} from "../../store/UserStore.ts";
import ContentRender from "../../components/content/ContentRender.vue";
import {PriMessageStatus} from "../../network/types/PriMessageStatus.ts";
import {scrollShortKeys, type ShortKey} from "../../utils/ShortKeys.ts";

const route = useRoute();
const router = useRouter();
const messageStore = useMessageStore();
const loading = ref(false)
const showReplyDialog = ref(false)
const data = ref<PriMsgBody>()
const total = ref(20)

// 回复私信标题
const title = ref()
// 回复私信正文
const content = ref()

const request = (route: any, force: boolean = false) => {
  const mid = Number(route.params.mid)
  const page = route.query.page ? Number(route.query.page) : 1
  loading.value = true
  console.log({mid, page})
  messageStore.read(mid, page, force).then(res => {
    console.log(res)
    data.value = res
    total.value = Math.max(total.value, res.total)
    loading.value = false
  }).catch(r => {
    console.error(r)
    loading.value = false
  })
}

const changePage = (p: number | undefined) => {
  if (!p) return
  scrollToTop()
  return router.push({query: {...route.query, page: p}, params: route.params});
}

const rowClass = (index: number) => {
  if (index % 2 === 0) {
    return "item-bg-color0"
  } else {
    return "item-bg-color1"
  }
}

const userByReply = (item: PriMsg): UserInfo | undefined => data.value?.userMap?.users[Number(item.userId)]


const avatarByReply = (item: PriMsg): string | undefined => {
  const avatars = userByReply(item)?.avatars;
  if (!avatars) return undefined

  // 从头像数组中随机选出一个
  if (avatars && avatars.length > 0) {
    return replaceAvatar(avatars[Math.floor(Math.random() * avatars.length)])
  }
}
onMounted(() => {
  request(route)
})

watch(route, (r) => {
  if (r.name === PriMsgRoute.READ) {
    request(r)
  }
})
const refresh = () => request(route, true)

const reply = (content: string, title: string) => {
  const mid = Number(route.params.mid)
  if (!mid || isNaN(mid)) return
  messageStore.reply(mid, content, title).then(res => {
    console.log(res)
    showReplyDialog.value = false
    refresh()
  }).catch(r => {
    console.error(r)
  })
}

// 快捷键
const shortKeys: ShortKey[] = [
  {title: '刷新', keys: ['alt', 'r'], action: refresh},
  ...scrollShortKeys,
]


</script>

<template>
  <div v-loading="loading" class="route-root">
    <!--快捷键-->
    <div v-if="!showReplyDialog" class="short-key-div">
      <template v-for="k in shortKeys">
        <span v-shortkey="k.keys" @shortkey="k.action">{{ k.title }}</span>
      </template>
    </div>
    <div>
      <el-button-group>
        <el-button type="primary" @click="refresh">刷新</el-button>
        <el-button v-if="data && !data.status.includes(PriMessageStatus.FROM_SYSTEM)" type="primary" @click="showReplyDialog=true">回复</el-button>
      </el-button-group>
    </div>
    <div v-if="data">
      <el-pagination :current-page="data.page" :page-size="20" :total="total"
                     hide-on-single-page
                     layout="prev, pager, next,jumper, total"
                     @current-change="changePage"/>
    </div>
    <!-- 私信消息列表-->
    <div v-if="data">
      <table class="reply-table">
        <tr v-for="(item, index) in data.data" :key="index" :class="rowClass(index)">
          <td>
            <!--用户名-->
            <span v-if="item.userId===0"></span>
            <reply-author-header v-else :user="userByReply(item)"/>

            <div v-if="userByReply(item)?.avatars" style="text-align: center">
              <el-image :src="avatarByReply(item)" class="user-avatar"/>
            </div>
          </td>
          <td>
            <div>
              <el-tag v-if="item.time">{{ item.time?.full }}</el-tag>
            </div>
            <div>
              <h4 v-if="item.title">{{ item.title }}</h4>
              <content-render :data="item.nodes || []"/>
            </div>
          </td>
        </tr>
      </table>
    </div>
    <!--回复私信-->
    <el-dialog v-model="showReplyDialog" title="回复私信">
      <el-input v-model="title" placeholder="标题(选填)"/>
      <el-input v-model="content" placeholder="正文(必填)" type="textarea"/>
      <el-button type="success" @click="reply(content,title)">发送</el-button>
    </el-dialog>
  </div>
</template>

<style scoped>

</style>